#include <sys/util.h>
#include "sample_instance.h"

/* 2.注册模块日志，模块名为module_inst，等级为DEBUG */
#include <logging/log.h>
#define SAMPLE_INSTANCE_MODULE_NAME module_inst
LOG_MODULE_REGISTER(SAMPLE_INSTANCE_MODULE_NAME, 4);


/* 该宏用于获取实例结构体遍历指针 */
#define SAMPLE_INSTANCE_PTR(idx) &sample_##idx##_info

/* 该宏用于生成实例，为每个实例注册日志，并进行初始化 */
#define SAMPLE_INSTANCE_DEVICE(idx) \
	LOG_INSTANCE_REGISTER(SAMPLE_INSTANCE_MODULE_NAME, inst##idx, 3); \
	struct sample_instance sample_##idx##_info = {		   \
		LOG_INSTANCE_PTR_INIT(log, SAMPLE_INSTANCE_MODULE_NAME, inst##idx)	   \
	};

/* 最多支持3个实例 */
#define SAMPLE_INSTANCE_NUM 3

/* 3.使用宏注册和初始化实例日志 */
SAMPLE_INSTANCE_DEVICE(0)
SAMPLE_INSTANCE_DEVICE(1)
SAMPLE_INSTANCE_DEVICE(2)


static struct sample_instance *sample_instace_ptr[]={
    SAMPLE_INSTANCE_PTR(0), 
    SAMPLE_INSTANCE_PTR(1), 
    SAMPLE_INSTANCE_PTR(2)};

struct sample_instance *sample_instance_open(uint8_t id)
{
    if(id < SAMPLE_INSTANCE_NUM){
        sample_instace_ptr[id]->cnt = 10;
        return sample_instace_ptr[id];
    }
    
    return NULL;
}

int sample_instance_close(struct sample_instance *inst)
{
    if(inst == NULL){
        return -1;
    }
    return 0;
}

int sample_instance_do(struct sample_instance *inst)
{
    if(inst == NULL){
        return -1;
    }

    /* 4.进行实例日志输入 */
	LOG_INST_INF(inst->log, "inst %p counter_value: %d", inst, inst->cnt);
    inst->cnt++;
    return 0;
}



void instance_logging(void)
{
    struct sample_instance *inst0 = sample_instance_open(0);
    struct sample_instance *inst1 = sample_instance_open(1);
    struct sample_instance *inst2 = sample_instance_open(2);

    sample_instance_do(inst0);
    sample_instance_do(inst1);
    sample_instance_do(inst2);
    sample_instance_header_do(inst0);

    sample_instance_close(inst0);
    sample_instance_close(inst1);
    sample_instance_close(inst2);

}